package com.software.avatar.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.software.avatar.R;
import com.software.avatar.entity.UserInfo;
import com.software.avatar.result.Result;
import com.software.avatar.utils.HostUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class LoginActivity extends AppCompatActivity {

    private TextView tv_register;
    private EditText edt_password;
    private EditText edt_phone;
    private Button btn_login;

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initViews();
        initEvents();
        initHandler();
    }

    private void initHandler() {
        handler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 101) {
                    Result<UserInfo> result = (Result<UserInfo>) msg.obj;
                    if (result.getCode() != 200) {
                        Toast.makeText(LoginActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
                    } else {
                        //提示登录成功， 并跳转到我的界面
                        Toast.makeText(LoginActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
                        gotoMine(result.getData());
                    }
                }
            }
        };
    }

    private void gotoMine(UserInfo data) {

        Intent intent = new Intent(
                LoginActivity.this,
                HomePageActivity.class
        );
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        Bundle bundle = new Bundle();
        bundle.putString("phone", data.getPhone());
        bundle.putString("password", data.getPassword());
        bundle.putString("avatar", data.getAvatar());
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void initEvents() {
        //跳转至注册
        tv_register.setOnClickListener(v -> {
            Intent intent = new Intent(
                    LoginActivity.this,
                    RegisterActivity.class
            );
            startActivity(intent);
        });
        btn_login.setOnClickListener(v -> {
            new Thread(){
                @Override
                public void run() {
                    String phone = edt_phone.getText().toString();
                    String password = edt_password.getText().toString();
                    login(phone, password);
                }
            }.start();
        });
        
    }

    private void login(String phone, String password) {
        String path = String.format(
                HostUtil.HOST + "/login?phone=%s&password=%s",
                phone,
                password
        );
        //访问后端
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置请求方式
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String readLine = br.readLine();
            Gson gson = new Gson();
            Result result = gson.fromJson(readLine, new TypeToken<Result<UserInfo>>() {
            }.getType());
            Message message = handler.obtainMessage();
            message.what = 101;
            message.obj = result;
            handler.sendMessage(message);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

    private void initViews() {
        tv_register = findViewById(R.id.tv_register);
        edt_phone = findViewById(R.id.edt_phone);
        edt_password = findViewById(R.id.edt_password);
        btn_login = findViewById(R.id.btn_login);
    }
}